package com.sto.stoapp.activity.administrator.system;

import android.media.AudioManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.widget.StoHomeActivity;

import sto.android.app.StoPdaKeyEvent;

public class SystemSoundSettingsActivity extends StoHomeActivity {

	private ProgressBar progressBar;

	private Button subButton, addButton;

	private AudioManager am;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.system_sound_settings);
		String broadType = getIntent().getStringExtra(
				HomeBroadAction.BROAD_TYPE);
		// 判断是管理员的系统设置还是业务内部的系统设置
		if (broadType != null && !broadType.equals("")) {
			this.setTitleBottom(R.string.system_sound, broadType);
		} else {
			this.setTitleBottom(R.string.system_sound,
					HomeBroadAction.ADMINISTRATOR_BROAD);
		}
		initWidget();
		initListener();
	}

	private void initListener() {
		// 减按钮
		subButton.setOnClickListener(new StoOnClickListener(this) {
			@Override
			public void mHonClick(View view) {
				// 减少音量,更新进度条
				am.adjustVolume(AudioManager.ADJUST_LOWER, 0);
				progressBar.setProgress(am.getStreamVolume(am.getRingerMode()));
				SoundManager.getInstance(SystemSoundSettingsActivity.this)
						.playKeyAndTouchSound();
			}
		});
		// 加按钮
		addButton.setOnClickListener(new StoOnClickListener(this) {
			@Override
			public void mHonClick(View view) {
				// 增加音量,更新进度条
				am.adjustVolume(AudioManager.ADJUST_RAISE, 0);
				progressBar.setProgress(am.getStreamVolume(am.getRingerMode()));
				SoundManager.getInstance(SystemSoundSettingsActivity.this)
						.playKeyAndTouchSound();
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		keyCode= StoApplication.getStoJni().getEventFuction(keyCode);
		if (keyCode == StoPdaKeyEvent.KEYCODE_VOLUME_DOWN) {
			// 可能由于点击物理按键后，我们还没来得及获取到最新数据，因此这里获得的音量依旧是点击物理按键前的音量
			progressBar.setProgress(am.getStreamVolume(am.getRingerMode()) - 1);
		} else if (keyCode == StoPdaKeyEvent.KEYCODE_VOLUME_UP) {
			progressBar.setProgress(am.getStreamVolume(am.getRingerMode()) + 1);
		}
		return super.onKeyDown(keyCode, event);
	}

	private void initWidget() {
		am = (AudioManager) getSystemService(AUDIO_SERVICE);
		subButton = (Button) findViewById(R.id.setting_minus);
		progressBar = (ProgressBar) findViewById(R.id.setting_progressBar);
		addButton = (Button) findViewById(R.id.setting_plus);
		progressBar.setMax(am.getStreamMaxVolume(am.getRingerMode()));
		// 获取当前铃声模式以及音量大小,设置到进度条
		progressBar.setProgress(am.getStreamVolume(am.getRingerMode()));
	}
}
